package com.tingyuge.thinking.spring.ioc.overview.dependency.injection;

import com.tingyuge.thinking.spring.ioc.overview.annotation.Supper;
import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import com.tingyuge.thinking.spring.ioc.overview.repository.UserRepository;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.Environment;

import java.util.Map;

/**
 * 依赖注入示例
 * 1.通过名称查找
 *
 * @author xiaodao
 * @version 1.0
 * @date 2021/6/15
 */
public class DependencyInjectionDemo {

    public static void main(String[] args) {
        /*配置 xml 配置文件*/
        //获取 spring 应用上下文
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("META-INF/dependency-injection-context.xml");
        //依赖来源1:自定义的bean
        UserRepository userRepository = beanFactory.getBean("userRepository", UserRepository.class);
        //依赖来源2: 依赖注入(内建依赖)
        System.out.println(userRepository.getBeanFactory());
//        System.out.println(beanFactory == userRepository.getBeanFactory());
        //依赖查找(错误)
//        System.out.println(beanFactory.getBean(BeanFactory.class));
        ObjectFactory<ApplicationContext> objectFactory = userRepository.getObjectFactory();
        System.out.println(objectFactory.getObject() == beanFactory);

        //依赖来源3: 容器内建bean
        Environment environmentBean = beanFactory.getBean(Environment.class);
        System.out.println("获取 environmentBean 类型的bean: "+ environmentBean);
    }

    private static void whoIsIOCContainer(UserRepository userRepository,BeanFactory beanFactory){
//        ConfigurableApplicationContext <--ApplicationContext  <---BeanFactory

        //AbstractRefreshableApplicationContext#getBeanFactory 是组合进来的
        //这个表达式为什么不成立
        System.out.println(userRepository.getBeanFactory() == beanFactory);
    }

}
